package org.backend.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.backend.pojo.entity.Product;
import org.backend.pojo.entity.Transaction;
import org.backend.pojo.entity.User;
import org.backend.pojo.entity.WxUser;
import org.backend.pojo.vo.ProductWithQuantityVO;
import org.backend.repository.ProductRepository;
import org.backend.repository.TransactionRepository;
import org.backend.repository.UserRepository;
import org.backend.service.EmailService;
import org.backend.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TransactionRepository transactionRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public void sendNotify(List<Product> productList, Integer transactionId) {
        List<ProductWithQuantityVO> transactionWithProducts = transactionRepository.getTransactionWithProducts(transactionId);
        StringBuilder emailContent = new StringBuilder();
        emailContent.append("亲爱的卖家，\n\n");
        emailContent.append("您发布的商品已成功售出，商品名称如下：\n");
        // 遍历 transactionList，将商品名称添加到邮件内容
        for (ProductWithQuantityVO t : transactionWithProducts) {
            emailContent.append("- ").append(t.getName()).append("\n");
        }
        emailContent.append("\n请与买家尽快联系，安排商品交付事宜。");

        Set<String> emails = new HashSet<>();
        for (Product p : productList) {
            Product productById = productRepository.getProductById(p.getProductId());
            if (productById.getUserId() == -1) {
                WxUser user = userRepository.findWxUserByOpenId(productById.getOpenid());
                emails.add(user.getEmail());
            } else {
                User user = userRepository.findUserByUserId(productById.getUserId());
                emails.add(user.getEmail());
            }
        }

        try {
            for (String email : emails) {
                // 发送邮件
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(fromEmail);
                message.setTo(email);
                message.setSubject("战神二手校园交易平台");
                message.setText(emailContent.toString());
                mailSender.send(message);
            }
        } catch (Exception e) {
            log.error("发送邮件失败", e);
            throw new RuntimeException("发送邮件失败，请稍后重试");
        }
    }

}